package com.hx.controller;


import com.hx.entity.User;
import com.hx.exception.WebException;
import com.hx.form.UserLoginForm;
import com.hx.form.UserRegisterForm;
import com.hx.result.ResponseEnum;
import com.hx.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 *  UserController
 * </p>
 *
 * @author zhangyiming
 * @since 2022-03-02
 */
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userRegisterForm 前台传的用户信息
     * @param bindingResult 错误信息
     * @return 登录页
     */
    @PostMapping("/register")
    /*@Valid注解的作用是：用于验证注解是否符合要求，直接加在变量user之前，
    在变量中添加验证信息的要求，当不符合要求时就会在方法中返回message 的错误提示信息。*/
    //错误信息封装到BindingResult中
    public String register(@Valid UserRegisterForm userRegisterForm , BindingResult bindingResult){
        //非空校验
        if (bindingResult.hasErrors()){
            log.info("[用户注册]-用户信息不能为空");
            throw new WebException(ResponseEnum.USER_INFO_NULL);
        }
        User register = userService.register(userRegisterForm);
        if (register == null){
            log.info("[用户注册]添加用户失败");
            throw new WebException(ResponseEnum.USER_REGISTER_ERROR);
        }
        return "redirect:/login";
    }

    /**
     * 用户登录
     * @param userLoginForm 前台传过来的用户信息
     * @param bindingResult 错误信息
     * @param session sessiom
     * @return 主页
     */
    @PostMapping("/login")
    public String login(@Valid UserLoginForm userLoginForm, BindingResult bindingResult, HttpSession session){
        //非空校验
        if(bindingResult.hasErrors()){
            log.info("[用户登录]用户信息不能为空");
            throw new WebException(ResponseEnum.USER_INFO_NULL);
        }
        User login = userService.login(userLoginForm);
        session.setAttribute("user",login);
        return "redirect:/productCategory/main";
    }
}

